<template>
  <div class="report-container-padding">
    <div class="buttonList">
      <el-button @click="handleSaveDraft">保存为草稿</el-button>
      <el-button type="primary" @click="handleSubmit">确认提交</el-button>
    </div>
    <div class="custom-divider"></div>
    <el-form ref="ruleFormRef" :model="formData" :rules="rules">
      <el-col :span="10">
        <el-form-item label="难题名称：" prop="name">
          <div class="problemButton">
            <el-input v-model="formData.name" placeholder="请输入" clearable />
            <el-button type="primary" @click="handleAiCheck">
              AI智能查重
            </el-button>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="10">
        <el-form-item label="提出单位：" prop="deptId">
          <el-tree-select
            v-model="formData.deptId"
            :data="reportingUnitOptions"
            :render-after-expand="false"
            placeholder="请选择"
            filterable
            clearable
            check-strictly
            :props="{
              value: 'id',
              label: 'name',
              children: 'children',
            }"
          />
        </el-form-item>
      </el-col>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="难题描述：" label-position="top" required>
            <el-col :span="12">
              <el-form-item
                label="一、建议主要研究内容"
                label-position="top"
                prop="mainResearchContent"
              >
                <el-input
                  v-model="formData.mainResearchContent"
                  type="textarea"
                  placeholder="请输入"
                  :rows="10"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="二、建议主要经济指标"
                label-position="top"
                prop="mainTechnoeconomicIndicators"
              >
                <el-input
                  v-model="formData.mainTechnoeconomicIndicators"
                  type="textarea"
                  placeholder="请输入"
                  :rows="10"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="descript">
              <el-form-item
                label="三、预期成果"
                label-position="top"
                prop="expectedOutcome"
              >
                <el-input
                  v-model="formData.expectedOutcome"
                  type="textarea"
                  placeholder="请输入"
                  :rows="10"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="descript">
              <el-form-item
                label="四、现场问题描述"
                label-position="top"
                prop="problemDescription"
              >
                <el-input
                  v-model="formData.problemDescription"
                  type="textarea"
                  placeholder="请输入"
                  :rows="10"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
  import type { FormInstance, FormRules } from 'element-plus'
  import {
    optionsProps,
    problemReportProps,
    resCreateProps,
    resDetailsProps,
  } from '../interface'
  import {
    postProblemCreate,
    putProblemUpdate,
    getPromblemDetails,
  } from '@/api/project/researchProblems'
  import { postDraftBoxCreate } from '@/api/project/drafts'
  import { getSimpleDeptList } from '@/api/system/dept'
  import { useDepartmentTree, DepartmentNode } from '@/utils/useDepartmentTree'
  import { useCloseTabNavigate } from '@/utils/useCloseTabNavigate'

  const { closeTabNavigate } = useCloseTabNavigate()

  const route = useRoute()
  // 表单实列
  const ruleFormRef = ref<FormInstance>()
  // 表单数据
  const formData = reactive<Partial<problemReportProps>>({})
  // 表单校验
  const rules = reactive<FormRules<problemReportProps>>({
    name: [{ required: true, message: '请输入难题名称', trigger: 'blur' }],
    deptId: [{ required: true, message: '请选择提出单位', trigger: 'change' }],
    mainResearchContent: [
      { required: true, message: '请输入建议主要研究内容', trigger: 'blur' },
    ],
    mainTechnoeconomicIndicators: [
      { required: true, message: '请输入建议主要经济指标', trigger: 'blur' },
    ],
    expectedOutcome: [
      { required: true, message: '请输入预期成果', trigger: 'blur' },
    ],
    problemDescription: [
      { required: true, message: '请输入现场问题描述', trigger: 'blur' },
    ],
  })

  // 草稿
  const handleSaveDraft = async () => {
    try {
      const params = {
        id: route.query?.id || '',
        type: 'PROBLEM',
        submitJson: JSON.stringify({
          ...formData,
          draftBoxId: route.query?.id || '',
        }),
      }
      const res: resCreateProps = await postDraftBoxCreate(params)
      if (res && res.code === 0) {
        ElMessage.success('保存难题草稿成功')
        closeTabNavigate()
      } else {
        ElMessage.error(`保存难题草稿失败: ${res.msg || '未知错误'}`)
      }
    } catch (e) {
      console.error('保存难题草稿失败', e)
    }
  }
  // 确认提交
  const handleSubmit = async () => {
    const valid = await ruleFormRef.value.validate()
    if (valid) {
      console.log('表单校验通过，提交数据:', formData)
      try {
        // if (props.componentData?.type === 'drafts') {
        //   res = await putProblemUpdate(formData)
        //   if (res && res.code === 0) {
        //     ElMessage.success('更新难题成功')
        //     closeTabNavigate({ name: 'researchProblems' })
        //   } else {
        //     ElMessage.error(`更新难题失败: ${res.msg || '未知错误'}`)
        //   }
        // } else {
        const params = {
          ...formData,
          draftBoxId: route.query?.id || '',
        }
        const res: resCreateProps = await postProblemCreate(params)
        if (res && res.code === 0) {
          ElMessage.success('创建难题成功')
          closeTabNavigate({ name: 'researchProblems' })
        } else {
          ElMessage.error(`创建难题失败: ${res.msg || '未知错误'}`)
        }
        // }
      } catch (e) {
        console.error('创建难题失败', e)
      }
    } else {
      console.error('表单校验未通过')
    }
  }
  // 路由实例
  const router = useRouter()
  // AI智能查重
  const handleAiCheck = () => {
    router.push({
      name: 'ProjectKnowledgeAi',
      query: { keywords: formData.name },
    })
  }

  // 获得难题明细  当从草稿中进入时
  const fetchProblemDetails = async () => {
    try {
      const res: resDetailsProps = await getPromblemDetails({
        id: route.query?.id,
        getType: 1,
      })
      if (res && res.code === 0 && res.data) {
        Object.assign(formData, res.data)
      } else {
        ElMessage.error(`获取难题详情失败: ${res?.msg || '未知错误'}`)
      }
    } catch (e) {
      console.error('获取难题详情失败', e)
    }
  }

  // 提出单位下拉框
  const reportingUnitOptions = ref<DepartmentNode[]>([])
  const handleDeptDetails = async () => {
    try {
      const res: any = await getSimpleDeptList()
      if (res && res.code === 0 && res.data) {
        reportingUnitOptions.value = useDepartmentTree(res.data || [])
      }
    } catch (e) {
      console.error('获取上报单位出错:', e)
    }
  }

  onMounted(() => {
    if (route.query?.getType === '1') {
      fetchProblemDetails()
    }
    handleDeptDetails()
  })
</script>

<style lang="scss" scoped>
  .report-container-padding {
    .buttonList {
      display: flex;
      align-items: center;
      justify-content: end;
    }

    .custom-divider {
      position: relative;
      height: 1px;
      margin: 20px 0;
      background-color: #edeff2;
    }

    .custom-divider::before {
      position: absolute;
      top: 0;
      right: -20px;
      left: -20px;
      height: 1px;
      content: '';
      background-color: #edeff2;
    }

    .problemButton {
      display: flex;
      align-items: center;
      width: 100%;

      .el-button {
        margin-left: 10px;
      }
    }

    .descript {
      margin-top: 20px;
    }
  }
</style>
